import React, { PureComponent } from 'react';
import { Modal, Form, Input, Row, Select } from 'antd';
import lodash from 'lodash';
import { NotificationTypeArray } from '../../../utils/enum';
// import classNames from 'classnames';
import styles from './NotificationConfigModalEditor.less';

@Form.create()
export default class NotificationConfigModalEditor extends PureComponent {

  // 重置组件
  reset = () => {
    const { form } = this.props;
    form.resetFields();
  }

  init = ({ notificationType }) => {
    const { form } = this.props;
    form.setFieldsValue({ notificationType });
  }

  // 保存
  onCreate = () => {
    const { form, onOk, notificationConfigData } = this.props;
    if (!(onOk instanceof Function)) return;
    form.validateFields({ force: true }, (err, formValues) => {
      if (err) return;
      const { notificationType, templateId, targetList } = formValues;
      onOk({ notificationType, templateId, targetList }, notificationConfigData);
    });
  }

  render() {
    const { notificationConfigData, addFlag, configExists, resetFunc, initFunc, visible, confirmLoading, onCancel, form } = this.props;
    const { getFieldDecorator, getFieldValue } = form;
    if (resetFunc instanceof Function) resetFunc(this.reset);
    if (initFunc instanceof Function) initFunc(this.init);
    const width = 650;
    const notificationType = getFieldValue('notificationType') || notificationConfigData.notificationType;
    const templateId = getFieldValue('templateId');
    return (
      <Modal
        width={800}
        visible={visible}
        confirmLoading={confirmLoading}
        title={`${addFlag ? '新增' : '编辑'}告警通知项`}
        okText={addFlag ? '新增' : '保存'}
        onCancel={onCancel}
        onOk={this.onCreate}
        maskClosable={false}
        bodyStyle={{ padding: '24px 24px 12px 24px' }}
      >
        <Form layout="inline" className={styles.form}>
          <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
            <Form.Item label="通知类型">
              {getFieldDecorator('notificationType', {
                initialValue: notificationConfigData ? notificationConfigData.notificationType : undefined,
                validateFirst: true,
                rules: [
                  { required: true, whitespace: true, message: '通知类型必填' },
                  {
                    validator(_, value, callback) {
                      const errors = [];
                      if (addFlag && value && lodash.trim(value) !== '' && lodash.trim(templateId) !== '') {
                        if (configExists instanceof Function) {
                          if (configExists(value, templateId)) {
                            errors.push("告警通知项重复");
                          }
                        }
                      }
                      callback(errors);
                    },
                  },
                ],
              })(
                <Select style={{ width }} placeholder="通知类型" disabled={!addFlag}>
                  {NotificationTypeArray.map(item => (<Select.Option key={item.value} value={item.value}>{`${item.label}`}</Select.Option>))}
                </Select>
              )}
            </Form.Item>
          </Row>
          <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
            <Form.Item label="通知模版">
              {getFieldDecorator('templateId', {
                initialValue: notificationConfigData ? notificationConfigData.templateId : undefined,
                validateFirst: true,
                rules: [
                  { required: true, whitespace: true, message: '通知模版必填' },
                  {
                    validator(_, value, callback) {
                      const errors = [];
                      if (addFlag && value && lodash.trim(value) !== '' && lodash.trim(notificationType) !== '') {
                        if (configExists instanceof Function) {
                          if (configExists(notificationType, value)) {
                            errors.push("告警通知项重复");
                          }
                        }
                      }
                      callback(errors);
                    },
                  },
                ],
              })(
                <Input placeholder="通知模版" style={{ width }} disabled={!addFlag} />
              )}
            </Form.Item>
          </Row>
          <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
            <Form.Item label={notificationType === 'email' ? '邮箱帐号' : '手机号码'}>
              {getFieldDecorator('targetList', {
                initialValue: notificationConfigData ? notificationConfigData.targetList : undefined,
                validateFirst: true,
                rules: [
                  { type: 'array', required: true, whitespace: true, min: 1, max: 512, message: '通知帐号必填' },
                  {
                    validator(_, value, callback) {
                      const errors = [];
                      if (value && value.length > 0) {
                        let test;
                        if (lodash.trim(notificationType) === 'email') {
                          test = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
                        } else if (lodash.trim(notificationType) === 'sms') {
                          test = /^1\d{10}$/;
                        }
                        if (test) {
                          for (let i = 0; i < value.length; i++) {
                            if (!test.test(value[i])) {
                              errors.push(`${notificationType === 'email' ? '邮箱帐号' : '手机号码'}格式不正确: ${value[i]}`);
                              break;
                            }
                          }
                        }
                      }
                      callback(errors);
                    },
                  },
                ],
              })(
                <Select
                  mode="tags"
                  style={{ width }}
                  notFoundContent={null}
                  // optionFilterProp={null}
                  // optionLabelProp={null}
                  // filterOption={false}
                  tokenSeparators={[',']}
                  dropdownStyle={{ display: 'none' }}
                  placeholder={`通知帐号, ${notificationType === 'email' ? '邮箱帐号' : notificationType === 'sms' ? '手机号码' : '请先选择“通知类型”'}(多个帐号使用“,”分隔)`}
                />
              )}
            </Form.Item>
          </Row>
        </Form>
      </Modal>
    );
  }
}
